<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Util\SqlServerUtil;
use App\Util\DBSql;
use Cookie;

class LoginController extends Controller
{

	protected $response = [
		"code" => 200,
		"message" => "接口请求成功",
		"result" => []
	];

    protected $SqlServer = null;

    public function __construct(Request $request){
        $temp = SqlServerUtil::getModel($request);
        if($temp){
            $this->SqlServer = $temp['SqlServer'];
        }
    }

	public function home(Request $request)
	{
		$auth = $request->cookie("wms_auth");
		
		return view('home')->with(['auth' => $auth]);
	}
	
	public function install(Request $request)
	{
		return view('welcome');
		
	}
	public function installDB(Request $request)
	{
		header("Content-type: text/html; charset=utf-8");
		
		set_time_limit(0);
		$serverinfo = $request->all();
		if(!$serverinfo['username'] || !$serverinfo['password'] ){
			showMsg(400,'数据库用户名，数据库密码不能为空');
		}
		
		if(!$serverinfo['ip'] || !$serverinfo['database'] ){
			showMsg(400,'参数设置不能为空');
		}
		$serverConfig = [ "UID" => $serverinfo['username'], "PWD" =>$serverinfo['password'], "Database" => 'master'];
		$sqlCon = sqlsrv_connect($serverinfo['ip'], $serverConfig);
		if($sqlCon){
			$file_path = public_path().'/DatabaseSql/00TOPGZ_Master.sql';
			$sql = DBSql::getSqlFromFile($file_path);
			$gzDB = SqlServerUtil::sqlexecTo($sqlCon ,$sql);
// 			$gzDB =1;
			//创建数据库
			if($gzDB){
				$serverConfig_1 = [ "UID" => $serverinfo['username'], "PWD" =>$serverinfo['password'], "Database" => $serverinfo['database']];
				$sqlCon_1 = sqlsrv_connect($serverinfo['ip'], $serverConfig_1);
				if($sqlCon_1){
					$sql_1 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/01TOPGZ_biaojiegou.sql");
					$gzDB_1 =  SqlServerUtil::sqlexecTo($sqlCon_1 ,$sql_1);
					
					$sql_2 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/02TOPGZ_quanxian.sql");
					$gzDB_2 =  SqlServerUtil::sqlexecTo($sqlCon_1 ,$sql_2);
					
					$sql_3 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/03TOPGZ_data.sql");
					$gzDB_3 =  SqlServerUtil::sqlexecTo($sqlCon_1 ,$sql_3);
					
					$sql_4 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/04TOPGZ_xushibu.sql",false,[],$stype=4);
					if($sql_4 && count($sql_4)>0){
						if(count($sql_4)>200){
							$each = 200;
							$total =count($sql_4); //数据总数
							$step= ceil($total/$each); 
							$j = 1;
							$s = $step;
							foreach ($sql_4 as $k=>$v)
							{
								$arr0=[];
								if($j > $step) break;
								$arr0 = array_slice($sql_4, ($step - $s) * $each, $each);
								$gzDB_4 =  SqlServerUtil::sqlexecToTO($sqlCon_1 ,implode($arr0, " ") );
								$j++;
								$s--;
							}
						}else{
							$gzDB_4 =  SqlServerUtil::sqlexecToTO($sqlCon_1 ,implode($sql_4, " "));
						}
					}
					$sql_5 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/05TOPGZ_censhu.sql");
					$gzDB_5 =  SqlServerUtil::sqlexecTo($sqlCon_1 ,$sql_5);
					
					$sql_6 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/06TOPGZ_dengji.sql");
					$gzDB_6 =  SqlServerUtil::sqlexecTo($sqlCon_1 ,$sql_6);
					
					$sql_7 = DBSql::getSqlFromFile( public_path()."/DatabaseSql/07TOPGZ_ziduankz.sql");
					$gzDB_7=  SqlServerUtil::sqlexecTo($sqlCon_1 ,$sql_7);
					
					$dataENV = [
							'DB_HOST' => $serverinfo['ip'],
							'DB_USERNAME' => $serverinfo['username'],
							'DB_PASSWORD' => $serverinfo['password'],
							'DB_DATABASE' => $serverinfo['database'],
					];
					$insdataENV = modifyEnv($dataENV);
					
					if($gzDB_7 && $gzDB_6 && $gzDB_5 && $gzDB_4 && $gzDB_3 && $gzDB_2 && $gzDB_1 && $insdataENV){
						showMsg(200,'数据库创建成功！');
					}
					showMsg(400,'数据库创建失败！');
					 
				}else{
					showMsg(400,'数据库连接信息不成功1！');
				}
			}else{
				showMsg(400,'数据库创建不成功！');
			}
		}else{
			showMsg(400,'数据库用户名或密码错误，连接失败！');
		}
	}
	
	

    public function index()
    {
    	return view('login');
    }

    public function login(Request $request){
    	$username = $request->get("username");
        $password = $request->get("password");
       // $password = md5($password);
        $sql ="select LoginEmail,employeeName,employeeID,CreatedBy,RolesID,inActive from Employee where LoginEmail='" . $username."' and pass='" .$password ."'";
        $user = SqlServerUtil::exec($this->SqlServer,$sql);
        
        if($user && count($user)>0){
    		$wms_auth = json_encode($user[0]);
    		$request->session()->put("wms_auth",$wms_auth);
    		Cookie::queue('wms_auth', $wms_auth, $minutes = 300, $path = null, $domain = null, $secure = false, $httpOnly = false);
    		$this->response['result'] = [
    				'LoginEmail' => $user[0]['LoginEmail'],
    				//'password' => $user[0]['password'],
    				'FName' => 'kangbo',
    				'employeeName'=> $user[0]['employeeName'],
    				'employeeID' => $user[0]['employeeID'],
    				'CreatedBy' => $user[0]['CreatedBy'],
    				'RolesID' => $user[0]['RolesID'],
    				'inActive' => $user[0]['inActive'],
    		];
    		$this->response['message'] = "Login Success";
	    	return response($this->response);
    	}else{
    		$this->response['code'] = 400;
    		$this->response['message'] = "Login Error、 password Error";
    		return response()->json($this->response);
    	}
       
    }



    //在判断用户表
    protected function isUserTable($db, $FName, $FSID){
        $FName = iconv( 'UTF-8', 'GBK', $FName);
        $SqlServer = sqlsrv_connect($db['ip'],[ "UID" => $db['dbUserName'], "PWD" => $db['dbUserPwd'], "Database" => $db['dbName']]);
    	//$user = SqlServerUtil::execSql($SqlServer, "select * from t_pdauser where FName='{$FName}' and FSID='{$FSID}'",3);
        // echo "select pda.FName,pda.FViewPrice,pda.FSID,cu.CustomerID,cu.ChiName,cu.CustomerType  FROM T_PDAUser as pda LEFT JOIN Customer as cu ON pda.FNumber = cu.CustomerID WHERE pda.FName = '{$FName}' AND pda.FSID = '{$FSID}' AND cu.CustomerType = '{$db['FTypeID']}'";return;
        $user = SqlServerUtil::execSql($SqlServer, "select pda.FName,pda.FViewPrice,pda.FSID,cu.CustomerID,cu.ChiName,cu.CustomerType  FROM T_PDAUser as pda LEFT JOIN Customer as cu ON pda.FNumber = cu.CustomerID WHERE pda.FName = '{$FName}' AND pda.FSID = '{$FSID}' AND cu.CustomerType = '{$db['FTypeID']}'");
    	if($user){
    		return $user[0];
    	}else{
    		return [];
    	}
    }
 
    //先判断是否在master上面是否存在该用户
    public function checkMasterExUser($user, $pwd){
    	$SqlServer = sqlsrv_connect(env('DB_HOST'),[ "UID" => env('DB_USERNAME'), "PWD" => env('DB_PASSWORD'), "Database" => env('DB_DATABASE')]);
    	$user = SqlServerUtil::execSql($SqlServer,"SELECT * FROM yd_user WHERE username = '{$user}' AND password = '{$pwd}'");
        if(count($user)){
            $user = $user[0];
        	$pdaUser = [
                "ip" => env('DB_HOST'),
                "dbName" => env('DB_DATABASE'),
                "dbUserName" => env('DB_USERNAME'),
                "dbUserPwd" => env('DB_PASSWORD'),
                "user_id" => $user['id'],
                "nickname" => $user['nickname'],
                "level" => $user['level']
            ];
            return $pdaUser;
        }
        return false;
    }
    
    
    
    
}
